﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CommonUtils
{
    public static class HttpUtil
    {
        public static string HttpPostJson(string url, string body, IDictionary<string, string> header, int timeOut, IDictionary<string, string> rspHeader)
        {
            string rst = "";
            Encoding enc1 = Encoding.UTF8;
            byte[] content = enc1.GetBytes(body);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            request.Timeout = timeOut * 1000;
            request.ReadWriteTimeout = timeOut * 1000;
            request.KeepAlive = false;
            request.ServicePoint.Expect100Continue = false;
            request.ContentLength = content.Length;
            //设置请求header
            foreach (var item in header)
            {
                request.Headers.Add(item.Key, item.Value);
            }

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(content, 0, content.Length);
            }

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream, enc1);
                rst = reader.ReadToEnd();
            }

            //收集响应header
            if (rspHeader == null)
            {
                rspHeader = new Dictionary<string, string>();
            }
            foreach (var item in response.Headers.AllKeys)
            {
                rspHeader.Add(item, response.Headers[item]);
            }

            if (response != null)
            {
                response.Close();
                response = null;
            }
            if (request != null)
            {
                request.Abort();//2018-7-31，增加
                request = null;
            }

            return rst;
        }

    }
}
